<template>
  <div>
    <van-nav-bar title="登录" />
    <van-form validate-first @failed="onFailed" @submit="LoginFn">
      <van-field
        v-model="user.mobile"
        name="mobile"
        placeholder="请输入手机号"
        label="手机号"
        autocomplete="off"
        required
        clearable
        :rules="[
          {
            require: true,
            pattern: /^1[3-9]\d{9}$/,
            message: '请输入11位的手机号',
          },
        ]"
      />
      <van-field
        v-model="user.code"
        name="code"
        placeholder="请输入密码"
        label="密码"
        type="password"
        autocomplete="off"
        required
        clearable
        :rules="[
          { require: true, pattern: /^\d{6}$/, message: '请输入6位的密码' },
        ]"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :loading="loading"
          :disabled="loading"
          loading-text="登录中..."
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { Login } from '@/api/user/index.js'
import { setStorage } from '@/utils/storage.js'
import EventBus from '@/utils/eventbus.js'
export default {
  name: 'MyLogin',
  data() {
    return {
      user: {
        mobile: '', // 手机号
        code: '', // 验证码(密码)code值必须是"246810"(字符串类型带引号), 不可以是数字类型
      },
      loading: false,
    }
  },
  methods: {
    onFailed(errorInfo) {
      // console.log(errorInfo)
    },
    // 登录->调用登录接口
    async LoginFn(val) {
      // console.log(val)
      this.loading = true
      try {
        const { data: res } = await Login(val)
        this.$notify({ type: 'success', message: '登录成功' })
        // console.log(res)
        this.$store.commit('setToken', res.data.token)
        // 向本地存储用于刷新token的值
        setStorage('refresh_token', res.data.refresh_token)
        // this.$router.push() 压栈 会产生历史记录 可以回退
        // this.$router.replace() 替换 不会产生历史记录
        if (this.$route.query.path === '/layout/user') {
          EventBus.$emit('getUserInfo')
        }
        this.$router.replace({
          // 先判断是否有用户上次访问的页面的路径 如果没有 直接跳转到首页
          path: this.$route.query.path || '/layout',
        })
      } catch (error) {
        this.$notify({ type: 'danger', message: '手机号或密码错误' })
        // console.log(error)
      }
      this.loading = false
    },
  },
}
</script>

<style lang="less" scoped>
/* /deep/ 就是把data-v-hash值选择器写到类名的前面 */
/deep/ .van-nav-bar__title {
  color: white;
}
</style>
